package com.jec.module.sysconfig.service.convertor;

import java.util.Arrays;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jec.module.sysconfig.dao.NumberEntryRepository;
import com.jec.module.sysconfig.dao.TerminalBusinessRepository;
import com.jec.module.sysconfig.dao.TerminalKeyConfigRepository;
import com.jec.module.sysconfig.entity.TerminalBusiness;
import com.jec.module.sysmonitor.dao.TerminalDeviceRepository;
import com.jec.utils.Response;

/**
 * Created by jeremyliu on 09/10/2016.
 */
@Service
public class TerminalBusinessConvertor implements Convertor<TerminalBusiness> {

	@Autowired
    private TerminalBusinessRepository terminalBusinessRepository;

    @Autowired
    private TerminalDeviceRepository terminalDeviceRepository;

    @Autowired
    private TerminalKeyConfigRepository terminalKeyConfigRepository;

    @Autowired
    private NumberEntryRepository numberEntryRepository;

    @Override
    public Response process(TerminalBusiness terminalBusiness) {
        Response response = Response.Builder().status(Response.STATUS_PARAM_ERROR);
        if(terminalDeviceRepository.findAllByCode(terminalBusiness.getDeviceNumber()).size() == 0)
            return response.message("终端号码不存在");

        if(terminalBusinessRepository.existsByKeyConfigIdAndDeviceNumberAndIdNot(
        		terminalBusiness.getKeyConfigId(), 
        		terminalBusiness.getDeviceNumber(), 
        		terminalBusiness.getId()))
            return response.message("终端该业务已配置");

        if(terminalKeyConfigRepository.findOne(terminalBusiness.getKeyConfigId())==null)
            return response.message("终端按键未配置");

        String[] members = terminalBusiness.getMemberList();
        if(numberEntryRepository.findAllByNumberIn(Arrays.asList(members)).size() != members.length)
            return response.message("成员号码不合法");
        return response.status(Response.STATUS_SUCCESS);
    }

    @Override
    public Response checkBeforeRemove(int id) {
        return null;
    }
}
